<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>类别管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <div style="margin-bottom: 20px;">
      <el-button type="primary" size="medium"
                 @click="$router.push('/sys-admin/product/category/add-new')">添加类别
      </el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>

      <el-table-column prop="icon" label="图标" width="70" align="center">
        <template slot-scope="scope">
        <el-avatar :size="30" :src="scope.row.icon" fit="contain"></el-avatar>
      </template>

      </el-table-column>

      <el-table-column prop="name" label="名称" width="200" header-align="center"
                       show-overflow-tooltip></el-table-column>

      <el-table-column prop="keywords" label="关键词列表" header-align="center"
                       :show-overflow-tooltip="true"></el-table-column>

      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>


<!--TODO 是否启用功能      -->
      <el-table-column label="是否启用" width="120" align="center">
        <template slot-scope="scope">
        <el-switch
            @change="toggleEnable(scope.row)"
            v-model="scope.row.enable"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc">
        </el-switch>
        </template>

      </el-table-column>

      <!--TODO 是否显示在导航栏功能      -->
      <el-table-column label="显示在导航栏" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleDisplay(scope.row)"
              v-model="scope.row.isDisplay"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </template>
      </el-table-column>


      <el-table-column label="子级类别" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.isParent == 0"
                     @click="showSubCategoryList(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align: right; margin: 10px auto;">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>

    <el-dialog title="修改类别" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px">

        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="关键词列表" prop="keywords">
          <el-input v-model="editForm.keywords"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="editForm.icon"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 当前类别列表的父级类别ID
      currentParentId: 0,
      // 浏览历史，此数据主要用于返回功能
      history: [],
      // 编辑对话框的可见性
      dialogFormVisible: false,
      // 编辑表单
      editForm: {
        id: '',
        icon: '',
        name: '',
        keywords: '',
        sort: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入类别名称', trigger: 'blur'},
          {min: 2, max: 15, message: '类别名称长度必须在 2 到 15 个字符', trigger: 'blur'}
        ],
        keywords: [
          {required: true, message: '请输入关键词列表', trigger: 'blur'},
          {min: 2, max: 50, message: '关键词列表长度必须在 2 到 50 个字符', trigger: 'blur'}
        ],
        icon: [
          {required: true, message: '请输入图标图片的URL', trigger: 'blur'},
          {min: 20, max: 200, message: '图标图片的URL长度必须在 20 到 200 个字符', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^([0-9]{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是 0~99 之间的数字', trigger: 'blur'}
        ]
      },
      // 编辑表单的label宽度
      formLabelWidth: '120px'
    }
  },
  methods: {
    openEditDialog(category) {
      let url = 'http://localhost:9180/category/standard?id=' + category.id;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        }
      });
    },
    //提交编辑表单
    submitEditForm() {
      let url = 'http://localhost:9180/category/update';
      console.log('url = ' + url);

      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      let localJwt = localStorage.getItem('localJwt')
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改类别成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadCategoryList();
        } else if (jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadCategoryList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    openDeleteConfirm(category) {
      this.$confirm('此操作将永久删除【' + category.id + '-' + category.name + '】类别，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(category);
      }).catch(() => {
      });
    },
    handleDelete(category) {
      let url = 'http://localhost:9180/category/' + category.id + '/delete';
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt')
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除类别成功！',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.loadCategoryList();
    },
    loadCategoryList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = 'http://localhost:9180/category/list?page=' + page;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt')
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadCategoryList();
  }
}
</script>